package storage

import (
	"fmt"
	"os"
	"path/filepath"
)

// LocalStorage implements Storage interface for local file system
type LocalStorage struct {
	basePath string
}

// NewLocalStorage creates a new LocalStorage instance
func NewLocalStorage(basePath string) *LocalStorage {
	return &LocalStorage{
		basePath: basePath,
	}
}

// Upload uploads a file to local storage
func (s *LocalStorage) Upload(filename string, data []byte) (string, error) {
	// Create file path
	filePath := filepath.Join(s.basePath, filename)

	// Create directory if not exists (including subdirectories)
	dir := filepath.Dir(filePath)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return "", fmt.Errorf("failed to create directory: %v", err)
	}

	// Check if file already exists
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		// File doesn't exist, save it
		if err := os.WriteFile(filePath, data, 0644); err != nil {
			return "", fmt.Errorf("failed to save file: %v", err)
		}
	}

	return filePath, nil
}

// Download downloads a file from local storage
func (s *LocalStorage) Download(filepath string) ([]byte, error) {
	data, err := os.ReadFile(filepath)
	if err != nil {
		return nil, fmt.Errorf("failed to read file: %v", err)
	}
	return data, nil
}

// Delete deletes a file from local storage
func (s *LocalStorage) Delete(filepath string) error {
	if err := os.Remove(filepath); err != nil && !os.IsNotExist(err) {
		return fmt.Errorf("failed to delete file: %v", err)
	}
	return nil
}

// GetURL returns the file path for local storage
func (s *LocalStorage) GetURL(filepath string) (string, error) {
	// For local storage, return the file path
	return filepath, nil
}
